//////////// SHARE CONSTANTS ////////////////////
var TYPE = new Object();

//Extention
TYPE.GET_TAB_ID = "GetTabId";
TYPE.GET_SITE_VALUE = "GetSiteValue";
TYPE.SEND_DATA_TAB_ID = "SendDataTabId";
TYPE.SEND_SITE_VALUE = "SendSiteValue";
TYPE.SEND_UNIT_PER_BET_VALUE = "SEND_UNIT_PER_BET_VALUE";
TYPE.START_MATCH = "StartMatch";
TYPE.STOP_MATCH = "StopMatch";
TYPE.LOG_INFO = "LogInfo";
TYPE.LOG_SUCCESS = "LogSucess";
TYPE.LOG_HIDDEN = "LogHidden";
TYPE.LOG_SITE_DATA = "LogSiteData";
TYPE.SET_UNIT_PER_BET = "SetUnitPerBet";

var SITE_ARRAY = new Array("mara", "padd", "plan", "pari", "beti", "favbet");
////////////////////////////////////////////////

//////////// LOCAL CONSTANTS ////////////////////
var ETENSION_ID = "jjoalchlfmefofpjmhbfpfahekljaojg";
var CURRENT_MATCH_ID = 1;
var CURRENT_MAX_TAB_INDEX = 1;
var CURRENT_MAX_PAIR_INDEX = 1;
var GlobalData = {};
var TIME_WAIT_CHECK_INPUT_PAIR = 200;
var TIME_WAIT_START = 500;
var MAX_INFO_ROWCOUNT = 500;
////////////////////////////////////////////////

///////////////////////////// EVENTS FUNCTIONS //////////////////////

// Window initialization code. Set up the various event handlers
window.addEventListener("load", function() {

    //Handle Test Button
    $("#btnTest").click(function() {
        HandleTestButton();
    });
    //Handle Start Button
    $("#btnStart").click(function() {
        HandleStartButton();
    });
    //Handle Stop Button
    $("#btnStop").click(function() {
        HandleStopButton();
    });
    //Handle Clear Button
    $("#btnClear").click(function() {
        HandleClearButton();
    });
    //Handle Add Tab Button
    $("#btnAddTab").click(function() {
        HandleAddTabButton();
    });
    //Handle Remove Tab Button
    $("#btnRemoveTab").click(function() {
        HandleRemoveTabButton();
    });

    //Handle Save records Button
    $("#btnSaveRecord").click(function(e) {

        var data = $("#hiddenLog").html().trim();
        if (!data) {
            e.preventDefault();
            return;
        }

        var date = new Date();
        var fileName = "LogRecords_" + date.getFullYear() + "_" + date.getMonth() + "_" + date.getDate();
        fileName += "_" + date.getHours() + "_" + date.getMinutes() + ".txt";
        createDownloadLink("#btnSaveRecord", data, fileName);
    });

    //Handle Add Pair Button
    $("#btnAddPair").click(function() {
        HandleAddPairButton();
    });

    //Handle Remove Pair Button
    $("#btnRemovePair").click(function() {
        HandleRemovePairButton();
    });

    //Handle Set Unit Per Bet
    $("#btnSetUnitPerBet").click(function() {
        HandleSetUnitPerBet();
    });

    RegisterTabChange();
});

//Handle Set Unit Per Bet
function HandleSetUnitPerBet()
{
    var value = $.trim($("#txtUnitPerBet").val());
    if (value)
    {
        var data = {
            Value: value
        };
        SendToExtension(TYPE.SET_UNIT_PER_BET, data, null);
    }
}

//Handle Test Button
function HandleTestButton() {
    var matchId = $("#mathTabs .active").attr("matchId");
    if (!CheckMatch(matchId)) {
        $("#match" + matchId + " .has-error .form-control").first().focus();
        return;
    }
}

//Handle Start Button
function HandleStartButton() {

    var matchId = $("#mathTabs .active").attr("matchId");
    if (!CheckMatch(matchId)) {
        $("#match" + matchId + " .has-error .form-control").first().focus();
        return;
    }

    //reset Log info row count
    GlobalData[matchId].LogInfoRowCount = 0;
    setTimeout(DoStart, TIME_WAIT_START, matchId);
}

//Handle Stop Button
function HandleStopButton() {
    var matchId = $("#mathTabs .active").attr("matchId");
    SendToExtension(TYPE.STOP_MATCH, matchId);
}

//Handle Clear Button
function HandleClearButton() {
    var matchId = $("#mathTabs .active").attr("matchId");

    //Clear message
    $("#match" + matchId + " .input-group").removeClass("has-error");
    $("#message" + matchId).html("");
    $("#information" + matchId).html("");
    $("#success" + matchId).html("");

    $("#match" + matchId + " .form-control").not("select").val("");
    $("#txtTeamOneName" + matchId).focus();
}

//Handle Add Tab Button
function HandleAddTabButton() {

    CURRENT_MAX_TAB_INDEX++;
    CURRENT_MAX_PAIR_INDEX++;

    //get teamplate HTML
    var tabTitleHtml = $("#tabTemplate").html().replace(/\[MATCH_NUMBER\]/g, CURRENT_MAX_TAB_INDEX);
    var tabContentHtml = $("#matchTemplate").html().replace(/\[MATCH_NUMBER\]/g, CURRENT_MAX_TAB_INDEX);
    tabContentHtml = tabContentHtml.replace(/\[PAIR_ID\]/g, CURRENT_MAX_PAIR_INDEX);
    var logHtml = $("#logTemplate").html().replace(/\[MATCH_NUMBER\]/g, CURRENT_MAX_TAB_INDEX);

    //add tab
    $("#btnAddTab").parent().before(tabTitleHtml);
    $("#matchTabContent").append(tabContentHtml);
    $("#log").append(logHtml);
    RegisterTabChange();
}

//Handle Remove Tab Button
function HandleRemoveTabButton() {
    var matchId = $("#mathTabs .active").attr("matchId");
    $("#message" + matchId).html("");

    //get match count
    var count = $("#mathTabs .match").length;
    if (count === 1)
    {
        ShowMessageString(matchId, "Can't remove all tabs.");
        return;
    }

    $("#mathTabs .active").remove();
    $("#matchTabContent .active").remove();
    $("#logMatch" + matchId).remove();

    $('#mathTabs a:first').tab('show');
    $('#mathTabs a:first').click();
}

//Handle Add Pair Button
function HandleAddPairButton() {

    var matchId = $("#mathTabs .active").attr("matchId");

    //Clear message and error
    $("#match" + matchId + " .input-group").removeClass("has-error");
    $("#message" + matchId).html("");

    //Check input pair name
    var txtPairName = $("#txtAddPairName");
    if (!txtPairName.val().trim()) {
        txtPairName.parent().addClass("has-error");
        ShowMessageString(matchId, "The name is require.");
        txtPairName.focus();
        return;
    }

    CURRENT_MAX_PAIR_INDEX++;
    //get teamplate HTML
    var html = $("#pairTemplate").html().replace(/\[PAIR_ID\]/g, CURRENT_MAX_PAIR_INDEX).replace(/\[PAIR_NAME\]/g, txtPairName.val());

    //add Pair
    $("#match" + matchId + " .pair:last").after(html);
    txtPairName.val("");
    $("#txtAValueOne" + CURRENT_MAX_PAIR_INDEX).focus();
}

//Handle Remove Pair Button
function HandleRemovePairButton() {
    var matchId = $("#mathTabs .active").attr("matchId");
    $("#message" + matchId).html("");

    var checkedElms = $("#match" + matchId + " input:checked");
    if (checkedElms.length === 0) {
        ShowMessageString(matchId, "Please select elements to remove.");
        return;
    }
    if (checkedElms.length === $("#match" + matchId + " .pair").length) {
        ShowMessageString(matchId, "Can't remove all.");
        return;
    }
    for (var i = 0; i < checkedElms.length; i++) {
        $(checkedElms[i]).parents(".pair").remove();
    }
}

function RegisterTabChange() {
    $('#mathTabs a').unbind("click");
    $('#mathTabs a').bind("click", function(e) {
        e.preventDefault();
        //Hide and show log
        var prevMatchId = $("#mathTabs .active").attr("matchId");
        $("#logMatch" + prevMatchId).hide();
        var currentMatchId = $(this).parent().attr("matchId");
        $("#logMatch" + currentMatchId).show();

        $(this).tab('show');
    });
}

/////////////////////////////// END EVENTS FUNCTIONS //////////////////////

///////////////////////////// PROCESS FUNCTIONS //////////////////////////////

function DoStart(matchId) {

    var data = GetMatch(matchId);
    SendToExtension(TYPE.START_MATCH, data, null);
}

function GetMatch(matchId) {

    var dtPairs = new Array();
    var pairs = $("#match" + matchId + " .pair");
    for (var i = 0; i < pairs.length; i++) {

        var pairId = $(pairs[i]).attr("pairId");
        dtPairs.push(GetPair(pairId));
    }
    var ASiteType = GetSiteType($("#txtAName" + matchId).val());
    var BSiteType = GetSiteType($("#txtBName" + matchId).val());
    return new MatchInfo(matchId, GlobalData[matchId].ATabId, ASiteType, GlobalData[matchId].BTabId, BSiteType, dtPairs);
}

function GetPair(pairId) {
    var sites = new Array();
    sites.push(GetSite(pairId, "A"));
    sites.push(GetSite(pairId, "B"));
    return new PairInfo(pairId, sites);
}

function GetSite(pairId, siteName) {
    var Team1Key = $("#txt" + siteName + "ValueOne" + pairId).val();
    var Team2Key = $("#txt" + siteName + "ValueTwo" + pairId).val();
    return new SiteInfo(Team1Key, Team2Key);
}

function CheckMatch(matchId) {

    //Clear
    $("#match" + matchId + " .input-group").removeClass("has-error");
    $("#message" + matchId).html("");
    $("#information" + matchId).html("");
    $("#success" + matchId).html("");

    //Check inputed data
    var messageArr = new Array();
    var label = null;

    //Check Site A URL
    var siteUrl = null;
    if (!CheckRequire("AName" + matchId)) {
        label = $("#lbl" + "AName" + matchId).html();
        messageArr.push(CM_Function.StringFormat("{0} is require.", label));
    } else {
        siteUrl = $("#txt" + "AName" + matchId);
        if (GetSiteType(siteUrl.val()) === "-1")
        {
            siteUrl.parent().addClass("has-error");
            label = $("#lbl" + "AName" + matchId).html();
            messageArr.push(CM_Function.StringFormat("{0} wasn't supported.", label));
        }
    }

    //Check Site B URL
    if (!CheckRequire("BName" + matchId)) {
        label = $("#lbl" + "BName" + matchId).html();
        messageArr.push(CM_Function.StringFormat("{0} is require.", label));
    } else {
        siteUrl = $("#txt" + "BName" + matchId);
        if (GetSiteType(siteUrl.val()) === "-1")
        {
            siteUrl.parent().addClass("has-error");
            label = $("#lbl" + "BName" + matchId).html();
            messageArr.push(CM_Function.StringFormat("{0} wasn't supported.", label));
        }
    }

    //Check require pairs
    if (messageArr.length === 0) {
        var pairs = $("#match" + matchId + " .pair");
        for (var i = 0; i < pairs.length; i++) {

            var pairId = $(pairs[i]).attr("pairId");
            CheckRequirePair(pairId, messageArr);
        }
    }

    //Check input
    if (messageArr.length === 0) {
        CheckInputMatch(matchId);
    }

    ShowMessage(matchId, messageArr);
    return messageArr.length === 0;
}

function CheckRequire(itemKey) {
    var item = $("#txt" + itemKey);
    if (!$.trim(item.val())) {
        item.parent().addClass("has-error");
        return false;
    }
    return true;
}

function CheckRequirePair(pairId, messageArr) {
    CheckRequireSite(pairId, "A", messageArr);
    CheckRequireSite(pairId, "B", messageArr);
}

function CheckRequireSite(pairId, siteName, messageArr) {

    var pairName = $("#pairName" + pairId).text();
    var label = null;
    //ValueOne
    if (!CheckRequire(siteName + "ValueOne" + pairId)) {
        label = $("#lbl" + siteName + "ValueOne" + pairId).html();
        messageArr.push(CM_Function.StringFormat("{0} - {1} is require.", pairName, label));
    }

    //ValueTwo
    if (!CheckRequire(siteName + "ValueTwo" + pairId)) {
        label = $("#lbl" + siteName + "ValueTwo" + pairId).html();
        messageArr.push(CM_Function.StringFormat("{0} - {1} is require.", pairName, label));
    }
}

function CheckInputMatch(matchId) {
    GlobalData[matchId] = {};

    //Check Site URL
    CheckSiteUrl(matchId, "AName");
    CheckSiteUrl(matchId, "BName");

    //Check input pairs
    setTimeout(function() {

        if ($("#message" + matchId).html().trim() !== "")
            return;

        var pairs = $("#match" + matchId + " .pair");
        for (var i = 0; i < pairs.length; i++) {

            var pairId = $(pairs[i]).attr("pairId");
            CheckInputPair(matchId, pairId);
        }
    }, TIME_WAIT_CHECK_INPUT_PAIR);
}

function CheckSiteUrl(matchId, siteName) {
    var siteUrl = $("#txt" + siteName + matchId).val();
    var data = {
        MatchId: matchId,
        SiteKey: siteName,
        SiteUrl: siteUrl
    };
    SendToExtension(TYPE.GET_TAB_ID, data, null);
}

function CheckInputPair(matchId, pairId) {
    CheckInputSite(matchId, pairId, "A");
    CheckInputSite(matchId, pairId, "B");
}

function CheckInputSite(matchId, pairId, siteName) {
    var valueOne = $("#txt" + siteName + "ValueOne" + pairId).val();
    var valueTwo = $("#txt" + siteName + "ValueTwo" + pairId).val();
    var siteType = GetSiteType($("#txt" + siteName + "Name" + matchId).val());
    var tabId = siteName === "A" ? GlobalData[matchId].ATabId : GlobalData[matchId].BTabId;

    var data = {
        MatchId: matchId,
        PairId: pairId,
        TabId: tabId,
        SiteType: siteType,
        ValueOne: {Key: siteName + "ValueOne", Value: valueOne},
        ValueTwo: {Key: siteName + "ValueTwo", Value: valueTwo}
    };
    SendToExtension(TYPE.GET_SITE_VALUE, data, null);
}

function GetSiteType(siteUrl) {
    var result = "-1";
    if (siteUrl.match(/marathonbet/gi)) {
        result = "0";
    } else if (siteUrl.match(/paddypower/gi)) {
        result = "1";
    } else if (siteUrl.match(/planetofbets/gi)) {
        result = "2";
    } else if (siteUrl.match(/parimatch/gi)) {
        result = "3";
    } else if (siteUrl.match(/betinternet/gi)) {
        result = "4";
    } else if (siteUrl.match(/favbet/gi)) {
        result = "5";
    }
    return result;
}

function ShowMessage(matchId, messageArr) {
    if (messageArr.length === 0)
        return;
    var message = "";
    for (var i = 0; i < messageArr.length; i++) {
        message += "<li>" + messageArr[i] + "</li>";
    }

    $("#message" + matchId).html(message);
}

function createDownloadLink(anchorSelector, str, fileName) {
    if (window.navigator.msSaveOrOpenBlob) {
        var fileData = [str];
        blobObject = new Blob(fileData);
        $(anchorSelector).click(function() {
            window.navigator.msSaveOrOpenBlob(blobObject, fileName);
        });
    } else {
        var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
        $(anchorSelector).attr("download", fileName);
        $(anchorSelector).attr("href", url);
    }
}

///////////////////////////// END PROCESS FUNCTIONS //////////////////////////////

///////////////////////////// RESPONSE FUNCTIONS //////////////////////////////

function ShowMessageString(matchId, message) {
    $("#message" + matchId).prepend("<li>" + message + "</li>");
}

function ShowInfo(matchId, message) {
    $("#information" + matchId).prepend("<li>" + message + "</li>");
}

function ShowSucess(matchId, message) {
    $("#success" + matchId).prepend("<li>" + message + "</li>");
}

function LogHiddenRecord(message) {
    $("#hiddenLog").prepend(message + "\n");
}

function LogSiteData(data) {
    GlobalData[data.MatchId].LogInfoRowCount++;
    if (GlobalData[data.MatchId].LogInfoRowCount === MAX_INFO_ROWCOUNT) {
        GlobalData[data.MatchId].LogInfoRowCount = 0;
        $("#information" + data.MatchId).html("");
    }

    var pairName = $("#pairName" + data.PairId).text();
    var message = CM_Function.StringFormat("{0} {1}{2}", data.Time, pairName, data.Message);
    $("#information" + data.MatchId).prepend("<li>" + message + "</li>");
}

function ShowNotification() {
    var path = chrome.runtime.getURL("/images/south-america-400x400.png");
    var options = null;
    options = {
        type: "basic",
        title: "Basic Notification",
        message: "Short message part",
        expandedMessage: "Longer part of the message"
    };
    options.iconUrl = path;
    options.buttons = [];
    chrome.notifications.create("id" + notID++, options, null);
}

function SendToExtension(type, data, sendResponse) {
    chrome.runtime.sendMessage(ETENSION_ID, {Type: type, Data: data}, sendResponse);
}

chrome.runtime.onMessageExternal.addListener(
        function(request, sender, sendResponse) {

            switch (request.Type) {
                case TYPE.SEND_DATA_TAB_ID:
                case TYPE.SEND_SITE_VALUE:
                    SetDataFromExtension(request.Type, request.Data);
                    break;
                case TYPE.LOG_INFO:
                    ShowInfo(request.Data.MatchId, request.Data.Message);
                    break;
                case TYPE.LOG_SUCCESS:
                    ShowSucess(request.Data.MatchId, request.Data.Message);
                    break;
                case TYPE.LOG_HIDDEN:
                    LogHiddenRecord(request.Data.Message);
                    break;
                case TYPE.LOG_SITE_DATA:
                    LogSiteData(request.Data);
                    break;
                case TYPE.SEND_UNIT_PER_BET_VALUE:
                    var message = CM_Function.StringFormat("The unit per bet changed to {0}", request.Data.Value);
                    var matchId = $("#mathTabs .active").attr("matchId");
                    ShowInfo(matchId, message);
                    break;
            }
        });

function SetDataFromExtension(type, data) {
    var message = null;
    var elm = null;
    switch (type) {
        case TYPE.SEND_DATA_TAB_ID:
            if (data.SiteKey === "AName") {
                GlobalData[data.MatchId].ATabId = data.TabId;
            } else {
                GlobalData[data.MatchId].BTabId = data.TabId;
            }

            if (data.TabId === -1) {
                elm = $("#txt" + data.SiteKey + data.MatchId);
                elm.parent().addClass("has-error");
                elm.focus();

                message = CM_Function.StringFormat("{0} is not open yet.", $("#lbl" + data.SiteKey + data.MatchId).html());
                ShowMessageString(data.MatchId, message);
            }
            break;
        case TYPE.SEND_SITE_VALUE:

            var pairName = $("#pairName" + data.PairId).text();
            var label = $("#lbl" + data.Key + data.PairId).html();
            var sitePriority = data.Key.indexOf("AValue") !== -1 ? "Main Site" : "Assistant Site";
            if (!data.Value) {
                elm = $("#txt" + data.Key + data.PairId);
                elm.parent().addClass("has-error");
                elm.focus();

                //message
                message = CM_Function.StringFormat("Can't get value of {0}-{1}-{2}.", sitePriority, pairName, label);
                ShowMessageString(data.MatchId, message);
            } else {
                message = CM_Function.StringFormat("The value of {0}-{1}-{2} is {3}.", sitePriority, pairName, label, data.Value);
                ShowInfo(data.MatchId, message);
            }
            break;
    }
}

///////////////////////////// END RESPONSE FUNCTIONS //////////////////////////////

